package nori6_server_controllers;
import java.io.*;
import java.net.*;

import nori6_common_protocol.Nori6IncomingMessage;

public class MessageController implements Runnable
{
	private Socket m_Client;
	public MessageController(Socket client)
	{
		m_Client = client;
	}
	
	@Override
	public void run() 
	{
		// Read the message
		try 
		{
			BufferedReader in =  new BufferedReader(new InputStreamReader(m_Client.getInputStream()));
			String msg = "", tmp;
			while((tmp = in.readLine()) != null)
			{
				msg += tmp;
			}
			
			// Parse the message
			Nori6IncomingMessage im = new Nori6IncomingMessage(msg);
			String response = RedirectAndHandleMessage(im);
			
	 		// Return the response
			if(response != null)
			{
				PrintWriter out = new PrintWriter(m_Client.getOutputStream(), true);
				out.println(response);
			}
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public String RedirectAndHandleMessage(Nori6IncomingMessage im)
	{
		switch(im.GetController())
		{
		case N6_USERS_CONTROLLER:
			return UsersController.HandleMessage(im);
		}
		return null;
	}
}
